package com.qdxwx.data.service.manager;

import com.qdxwx.common.exception.BusinessException;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.mapper.manager.*;
import com.qdxwx.models.manager.*;
import com.qdxwx.models.teacher.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户 业务层处理
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private ManagerPostMapper managerPostMapper;

    @Autowired
    private ManagerRoleMapper managerRoleMapper;

    @Override
    public List<Manager> getList(Manager manager, PageRequest page) {
        return managerMapper.selectList(manager, page);
    }

    @Override
    public long count(Manager manager) {
        return managerMapper.selectCount(manager);
    }

    /**
     * 查询已分配用户角色列表
     */
    @Override
    public List<Manager> getAllocatedList(Manager manager, PageRequest page) {
        return managerMapper.selectAllocatedList(manager, page);
    }

    @Override
    public long countAllocated(Manager manager) {
        return managerMapper.selectAllocatedCount(manager);
    }

    /**
     * 查询未分配用户角色列表
     */
    @Override
    public List<Manager> getUnallocatedList(Manager manager, PageRequest page) {
        return managerMapper.selectUnallocatedList(manager, page);
    }

    @Override
    public long countUnallocated(Manager manager) {
        return managerMapper.selectUnallocatedCount(manager);
    }

    /**
     * 通过用户名查询用户
     *
     * @param loginName 用户名
     * @return 用户对象信息
     */
    @Override
    public Manager getByLoginName(String loginName) {
        return managerMapper.selectManagerByLoginName(loginName);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param mobile 手机号码
     * @return 用户对象信息
     */
    @Override
    public Manager getByMobile(String mobile) {
        if (TKString.isMobile(mobile)) {
            return managerMapper.selectManagerByMobile(mobile);
        }
        return null;
    }


    /**
     * 通过用户ID查询用户
     *
     * @param managerId 用户ID
     * @return 用户对象信息
     */
    @Override
    public Manager get(int managerId) {
        if (managerId < 1) return null;
        return managerMapper.selectManagerById(managerId);
    }

    /**
     * 通过用户ID查询用户和角色关联
     *
     * @param managerId 用户ID
     * @return 用户和角色关联列表
     */
    @Override
    public List<ManagerRole> getRolesByManagerId(int managerId) {
        return managerRoleMapper.selectManagerRolesByManagerId(managerId);
    }

    @Override
    public int delete(int id) {
        //超级管理员不允许删除
        if (id == 1) return 0;
        Manager manager = get(id);
        if (manager == null) return 0;
        int row = managerMapper.deleteById(id);
        if (row > 0) {
            managerRoleMapper.deleteManagerRoleByManagerId(id);
            managerPostMapper.deleteByManagerId(id);
        }
        return row;
    }

    /**
     * 新增保存用户信息
     *
     * @param manager 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insert(Manager manager) {
        // 新增用户信息
        manager.setUpdateTime(LocalDateTime.now());
        manager.setCreateTime(LocalDateTime.now());
        int rows = managerMapper.insertManager(manager);
        if (rows > 0) {
            // 新增用户岗位关联
            insertPosts(manager);
            // 新增用户与角色管理
            insertRoles(manager);
        }
        return manager.getManagerId();
    }

    @Override
    @Transactional
    public int updateWithAuth(Manager manager) {
        manager.setUpdateTime(LocalDateTime.now());
        int row = managerMapper.updateManager(manager);
        if (row > 0) {
            insertRoles(manager);
            insertPosts(manager);
        }
        return row;
    }

    /**
     * 修改用户个人详细信息
     *
     * @param manager 用户信息
     * @return 结果
     */
    @Override
    public int update(Manager manager) {
        manager.setUpdateTime(LocalDateTime.now());
        return managerMapper.updateManager(manager);
    }

    /**
     * 修改用户密码
     *
     * @param manager 用户信息
     * @return 结果
     */
    @Override
    public int resetManagerPwd(Manager manager) {
        return update(manager);
    }

    /**
     * 用户授权角色
     *
     * @param manager 用户对象
     */
    @Override
    public void insertRoles(Manager manager) {
        managerRoleMapper.deleteManagerRoleByManagerId(manager.getManagerId());
        Integer[] roleIds = manager.getRoleIds();
        if ((null != roleIds)) {
            // 新增用户与角色管理
            List<ManagerRole> list = new ArrayList<>();
            for (Integer roleId : roleIds) {
                ManagerRole ur = new ManagerRole();
                ur.setManagerId(manager.getManagerId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                managerRoleMapper.batchManagerRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param manager 用户对象
     */
    @Override
    public void insertPosts(Manager manager) {
        Integer[] postIds = manager.getPostIds();
        managerPostMapper.deleteByManagerId(manager.getManagerId());
        if ((null != postIds)) {
            // 新增用户与岗位管理
            List<ManagerPost> list = new ArrayList<>();
            for (Integer postId : postIds) {
                ManagerPost up = new ManagerPost();
                up.setManagerId(manager.getManagerId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                managerPostMapper.insertPosts(list);
            }
        }
    }

    @Override
    public boolean checkLoginName(String loginName) {
        return managerMapper.checkLoginName(loginName) > 0;
    }

    @Override
    public boolean checkMobile(String mobile) {
        return managerMapper.checkMobile(mobile) > 0;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param manager 用户信息
     */
    @Override
    public void checkUserAllowed(Manager manager) {
        if (manager.isAdmin()) {
            throw new BusinessException("不允许操作超级管理员用户");
        }
    }

    @Override
    public String getRoleGroup(int managerId) {
        List<Role> list = roleMapper.selectRolesByManagerId(managerId);
        StringBuilder idsStr = new StringBuilder();
        for (Role role : list) {
            idsStr.append(role.getRoleId()).append(",");
        }
        if (TKString.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String getPostGroup(int managerId) {
        List<Post> list = postMapper.selectPostsByManagerId(managerId);
        StringBuilder idsStr = new StringBuilder();
        for (Post post : list) {
            idsStr.append(post.getPostId()).append(",");
        }
        if (TKString.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 用户状态修改
     *
     * @param manager 用户信息
     * @return 结果
     */
    @Override
    public int updateDisabled(Manager manager) {
        if (manager.getManagerId() < 1) return 0;
        return managerMapper.updateDisabled(manager);
    }

    @Override
    public Manager getBySearchName(String searchKey) {
        if (searchKey == null) return null;
        searchKey = searchKey.trim();
        if (searchKey.length() < 1 || searchKey.length() > 50) return null;
        if (TKString.isMobile(searchKey)) {
            return managerMapper.selectManagerByMobile(searchKey);
        } else {
            return managerMapper.selectManagerByLoginName(searchKey);
        }
    }

    @Override
    public int insertByTeacher(Teacher teacher) {
        Manager manager = getByMobile(teacher.getMobile());
        if (manager != null) {
            if (manager.getUserId() < 1 && teacher.getUserId() > 0) {
                manager.setUserId(teacher.getUserId());
                update(manager);
            }
            return manager.getManagerId();
        }
        manager = new Manager();
        manager.setUserId(teacher.getUserId());
        manager.setCompanyId(1);
        manager.setManagerName(teacher.getName());
        manager.setMobile(teacher.getMobile());
        manager.setLoginName(teacher.getMobile());
        manager.setRoleIds(TKConvert.toIntArray("10"));
        manager.setPostIds(TKConvert.toIntArray("5"));
        manager.setSex(2);
        manager.setAvatar(teacher.getAvatar());
        manager.setLoginPwd(TKConvert.toMD5(TKString.getRanString(10)));
        manager.setIsDisabled(0);
        manager.setCreateTime(LocalDateTime.now());
        return insert(manager);
    }

    @Override
    public int updateCombine(long userId1, long userId2) {
        if(userId1 < 1 || userId2 < 1){
            throw new RuntimeException("更新管理员：参数错误");
        }
        return managerMapper.updateCombine(userId1, userId2);
    }
}
